package sk.ygor.xtemplate;

import java.util.LinkedHashMap;
import java.util.Map;

public class Block implements Part {

    private String name;

    private StringBuilder parsedData;

    private Map<String, Part> parts;

    public Block(String name) {
        parts = new LinkedHashMap<String, Part>();
        this.name = name;
		parsedData = new StringBuilder();
	}

    public void addPart(Part part, String name) {
        parts.put(name, part);
    }

    public Map<String, Object> getParts() {
        return new LinkedHashMap<String, Object>(parts);
    }

    public String getName() {
        return name;
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
		sb.append("+[").append(name).append("]\n");
        for (Object b : parts.values()) {
            sb.append(b.toString());
        }
		sb.append("-[").append(name).append("]\n");
        return sb.toString();
    }

	public void parse(Map<String, Object> space) throws XTemplateException {
		for (Part b: parts.values()) {
			parsedData.append(b.getText(space));
		}
	}


	public String getText(Map<String, Object> space) {
		String result = parsedData.toString();
		parsedData = new StringBuilder();
		return result;
	}

	public Block getChildBlock(String name) {
		try {
			return (Block) parts.get(name);
		} catch (Exception e) {
			return null;
		}
	}
}
